package main

import (
	"fmt"
	"math/rand"
	"time"
)

func main() {
	message := make(chan int, 10)
	done := make(chan bool)
	defer close(message)
	go producer("producerA", message, done)
	go producer("producerB", message, done)
	go consumer("consumerA", message, done)
	go consumer("consumerB", message, done)

	time.Sleep(30 * time.Second)
	done <- true
	fmt.Println("main exit")
}

func producer(name string, ch chan<- int, done chan bool) {
	ticker := time.NewTicker(1 * time.Second)
	for _ = range ticker.C {
		select {
		case <-done:
			fmt.Printf("producer %s exit\n", name)
			return
		default:
			rand.Seed(time.Now().UnixNano())
			n := rand.Intn(10)
			fmt.Printf("producer %s : %d\n", name, n)
			ch <- n
		}
	}
}

func consumer(name string, ch <-chan int, done chan bool) {
	ticker := time.NewTicker(1 * time.Second)
	for _ = range ticker.C {
		select {
		case <-done:
			fmt.Printf("consumer %s exit\n", name)
			return
		default:
			n := <-ch
			fmt.Printf("consumer %s: %d\n", name, n)
		}
	}
}
